<template>
  <div class="container"> 
    <!-- 导航头 -->
    <van-nav-bar
      title="收货地址"
      left-arrow
      @click-left="handleGoBack" 
      fixed
    />
    
    <!-- 表单区域 -->
    <div class="address-form-container">
      <div class="form-wrapper">
        <van-form>
          <!-- 收件人 -->
          <van-field
            v-model="formData.receiverName"
            label="收件人"
            placeholder="请输入收件人姓名"
            required
            class="custom-field"
          />
          
          <!-- 联系方式 -->
          <van-field
            v-model="formData.receiverPhone"
            label="联系方式"
            placeholder="请输入手机号"
            type="tel"
            required
            class="custom-field"
          />
          
          <!-- 行政区域 -->
          <van-field
            v-model="formData.region"
            label="行政区域"
            placeholder="如：北京市 朝阳区"
            required
            class="custom-field"
          />
          
          <!-- 详细地址 -->
          <van-field
            v-model="formData.detailAddress"
            label="详细地址"
            placeholder="如：XX街道XX号"
            required
            class="custom-field"
          />
          
          <!-- 默认地址选项 -->
          <van-checkbox v-model="formData.isDefault" class="default-checkbox">
            设为默认地址
          </van-checkbox>
        </van-form>
      </div>
    </div>

    <!-- 底部新增按钮 -->
    <van-button 
      class="new-btn"
      round 
      block 
      @click="handleAddAddress"
      :loading="isSubmitting"
    >
      新 增
    </van-button>
  </div> 
</template>

<script setup name="AddressDetail">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { emitter } from '../utils/eventBus';
import { insertAddress ,setDefaultAddress} from '../api/index';
// 假设从缓存中获取当前登录用户ID（实际项目中根据登录逻辑获取）
//import { getCurrentUserId } from '../utils/auth';


const router = useRouter();
const isSubmitting = ref(false);

// 表单数据
const formData = reactive({
  receiverName: '',       
  receiverPhone: '',     
  region: '',            
  detailAddress: '',      
  isDefault: 0,           
  //userId: getCurrentUserId() // 关联当前用户ID（必须传递）
  userId:1
});


// 提交地址
const handleAddAddress = async () => {
  // 表单校验
  if (!formData.receiverName) return showToast('请输入收件人');
  if (!formData.receiverPhone) return showToast('请输入手机号');
  if (!/^1\d{10}$/.test(formData.receiverPhone)) return showToast('手机号格式错误');
  if (!formData.region) return showToast('请输入行政区域');
  if (!formData.detailAddress) return showToast('请输入详细地址');
  if (!formData.userId) return showToast('用户信息异常，请重新登录');

  isSubmitting.value = true;
  try {
    const submitData = {
      ...formData,
      isDefault: formData.isDefault ? 1 : 0 // 勾选时传1，否则传0
    };

    const res = await insertAddress(submitData);

    //默认地址
    if (submitData.isDefault === 1) {
      await setDefaultAddress(res); // res是新增的地址ID
    }
      showToast('地址新增成功');
  
    emitter.emit('addAddress', {
      ...formData,
      id: res 
    });

      
      setTimeout(() => {
        router.push('/address');
      }, 300);

  } catch (error) {
    console.error('新增地址接口调用失败：', error);
    showToast('网络异常，新增失败');
  } finally {
    isSubmitting.value = false;
  }
};

// 返回上一页
const handleGoBack = () => {
   router.push({name:"address"})
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-top: 46px;
  padding-bottom: 80px;
}

.address-form-container {
  padding: 16px;
}

.form-wrapper {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.custom-field {
  --van-field-label-width: 80px;
  --van-field-input-text-align: right;
  margin: 0 0 12px 0 !important;
  border-bottom: 1px solid #f5f5f5;
}

.default-checkbox {
  margin: 10px 0 0 80px;
  color: #666;
}

.new-btn {
  width: 300px;
  margin: 0 auto;
  background-color: #FFD700;
  color: #333;
  font-weight: bold;
}
</style>
